import { ref, reactive, onMounted, onUnmounted } from 'vue';

export function useBtnDrag(handleAi) {
    const draggableBtn = ref(null);
    const isDragging = ref(false);
    const initialX = ref(0);
    const initialY = ref(0);
    const currentX = ref(0);
    const currentY = ref(0);
    const btnStyle = reactive({});

    let dragStartX = 0;
    let dragStartY = 0;
    const dragThreshold = 5;

    const startDrag = (e) => {
        isDragging.value = true;
        initialX.value = e.clientX - currentX.value;
        initialY.value = e.clientY - currentY.value;
        dragStartX = e.clientX;
        dragStartY = e.clientY;

        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', stopDrag);
    };

    const drag = (e) => {
        if (!isDragging.value) return;
        e.preventDefault();

        const btnWidth = draggableBtn.value.offsetWidth;
        const btnHeight = draggableBtn.value.offsetHeight;
        const maxX = window.innerWidth - btnWidth;
        const maxY = window.innerHeight - btnHeight;

        let newX = e.clientX - initialX.value;
        let newY = e.clientY - initialY.value;
        newX = Math.max(0, Math.min(newX, maxX));
        newY = Math.max(0, Math.min(newY, maxY));

        currentX.value = newX;
        currentY.value = newY;
        updatePosition();
    };

    const stopDrag = () => {
        isDragging.value = false;
        document.removeEventListener('mousemove', drag);
        document.removeEventListener('mouseup', stopDrag);
        dragStartX = dragStartY = 0;
    };

    const updatePosition = () => {
        btnStyle.left = `${currentX.value}px`;
        btnStyle.top = `${currentY.value}px`;
    };

    const handleClick = (e) => {
        if (isDragging.value &&
            Math.abs(e.clientX - dragStartX) < dragThreshold &&
            Math.abs(e.clientY - dragStartY) < dragThreshold) {
            handleAi();
        }
    };

    onMounted(() => {
        // 初始化在右下角（保留 20px 边距）
        const initPosition = () => {
            if (draggableBtn.value) {
                currentX.value = window.innerWidth - draggableBtn.value.offsetWidth - 20;
                currentY.value = window.innerHeight - draggableBtn.value.offsetHeight - 20;
                updatePosition();
            }
        }

        initPosition();
        // 添加窗口 resize 监听
        const resizeHandler = () => {
            initPosition();
        };
        window.addEventListener('resize', resizeHandler);

        // 修改原有的卸载逻辑
        onUnmounted(() => {
            window.removeEventListener('resize', resizeHandler);
        });
    });


    return {
        draggableBtn,
        btnStyle,
        startDrag,
        handleClick
    };
}
